<template>
  <view class="container">
    <cu-custom bgColor="bg-green" :isBack="true">
      <block slot="backText">返回</block>
      <block slot="content">月计划配置详情</block>
    </cu-custom>

    <view class="bg-top bg-green">
      <view class="top-box shadow">
        <view class="qh-title text-bold text-blue text-xl u-text-center">
          <text></text>
        </view>

        <view class="cu-list menu">
          <!-- 账本选择 -->
          <view class="cu-item" style="padding: 0">
            <scroll-view scroll-x class="bg-white" style="height: 165upx" scroll-y>
              <view class="cu-list grid col-5">
                <view class="justify-center" v-for="(item, index) in books" :key="index" @click="changeBookClass(item)">
                  <view
                    class="cu-avatar round lg margin-xs iconfont"
                    :class="item.iconName"
                    :style="item.value === plan.accountBookId ? 'background-color: #1cbbb4' : ''"
                  ></view>
                  <view>{{ item.label }}</view>
                </view>
              </view>
            </scroll-view>
          </view>

          <!-- 类型选择 -->
          <view class="cu-item" style="padding: 0">
            <scroll-view scroll-x class="bg-white" style="height: 315upx" scroll-y>
              <view class="cu-list grid col-5">
                <view class="justify-center" v-for="(item, index) in types" :key="index" @click="changeTypeClass(item)">
                  <!-- 支出 -->
                  <view
                    class="cu-avatar round lg margin-xs iconfont"
                    :class="item.iconName"
                    :style="item.value === plan.accountCategoryId ? 'background-color: #e03997' : ''"
                  ></view>
                  <view>{{ item.label }}</view>
                </view>
              </view>
            </scroll-view>
          </view>

          <view class="cu-item" style="padding: 0">
            <view class="content">
              <text class="cuIcon-writefill text-blue margin-right-xs"></text>
              <text class="text-black">月计划支出金额</text>
            </view>
            <view class="action">
              <view class="cu-tag round bg-green light" @tap="keyBoardShow = true">
                {{ plan.expenditureAmt ? plan.expenditureAmt : '请点击输入金额' }}
              </view>
            </view>
          </view>

          <view v-if="expenditureAmtSummary" class="cu-item" style="padding: 0">
            <view class="content">
              <text class="cuIcon-writefill text-red margin-right-xs"></text>
              <text class="text-black">当前支出金额</text>
            </view>
            <view class="action">
              <view class="cu-tag round bg-red light">
                {{ expenditureAmtSummary }}
              </view>
            </view>
          </view>

          <!-- 数字键盘 -->
          <u-keyboard
            mode="number"
            v-model="keyBoardShow"
            :mask="false"
            :tooltip="false"
            @change="valChange"
            @backspace="backspace"
          ></u-keyboard>

          <view class="cu-item" style="padding: 0">
            <view class="content">
              <text class="cuIcon-timefill text-orange margin-right-xs"></text>
              <text class="text-black">计划月份</text>
            </view>
            <view class="action">
              <view @tap="timeShow = true" class="cu-tag round bg-orange light">{{ plan.planDate }}</view>
            </view>
          </view>

          <!-- 计划月份选择 -->
          <u-picker
            title="计划月份"
            mode="time"
            v-model="timeShow"
            :default-time="plan.planDate"
            :params="params"
            end-year="2099"
            @confirm="timeConfirm"
          ></u-picker>
        </view>
      </view>

      <!-- 保存按钮 -->
      <view class="padding-lr flex margin-top-sm" style="justify-content: space-between; width: 750rpx">
        <button class="saveRecord" :style="[inputStyle]" @tap="update" style="width: 100%">保存记录</button>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      plan: {
        id: null,
        expenditureAmt: '',
        planDate: '',
        accountBookId: 1,
        accountCategoryId: 1,
        bookName: '日常',
        typeName: '美食'
      },
      timeShow: false,
      params: {
        year: true,
        month: true,
        day: false,
        hour: false,
        minute: false,
        second: false,
        timestamp: false
      },
      books: [],
      types: [],
      selBook: [0],
      expenditureAmtSummary: null,
      bookShow: false,
      keyBoardShow: false,
      confirmIndex: 0
    }
  },
  computed: {
    inputStyle() {
      let style = {}
      if (this.plan.expenditureAmt && this.plan.planDate && this.plan.accountBookId && this.confirmIndex == 0) {
        style.color = '#fff'
        style.backgroundColor = this.$u.color['success']
      }
      return style
    }
  },
  async onLoad(option) {
    this.getDetail(option.id)
    this.getAccountBookList()
    this.getExpenditureTypeList()
  },
  methods: {
    async getDetail(id) {
      const res = await this.$u.api.getAccountPlanDetail(id)
      this.plan = res
      this.plan.expenditureAmt = String(this.plan.expenditureAmt)
			this.getExpenditureAmtSummary()
    },
    /**
     * 获取所有的账本信息
     */
    async getAccountBookList() {
      const res = await this.$u.api.getAccountBookList()
      let data = JSON.parse(JSON.stringify(res))

      this.books = []
      data.forEach((item) => {
        let dat = {
          label: item.name,
          value: item.id,
          iconName: item.iconName
        }

        this.books.push(dat)
      })
    },
    /**
     * 获取所有的支出类别类型
     */
    async getExpenditureTypeList() {
      const res = await this.$u.api.getTypesByCategory(1)
      let data = JSON.parse(JSON.stringify(res))

      data.forEach((item) => {
        let dat = {
          label: item.typeName,
          value: item.id,
          iconName: item.iconName
        }

        this.types.push(dat)
      })
    },
    /**
     * 账本选择编号赋值
     * @param {Object} e
     */
    changeBookClass(e) {
      this.plan.accountBookId = e.value
      this.plan.bookName = e.label
    },
    /**
     * 类型选择编号赋值
     * @param {Object} e
     */
    changeTypeClass(e) {
      this.plan.accountCategoryId = e.value
      this.plan.typeName = e.label
      this.getExpenditureAmtSummary()
    },
    /**
     * 获取支出金额数据
     */
    async getExpenditureAmtSummary() {
      let params = {
        accountBookId: this.plan.accountBookId,
        accountCategoryId: this.plan.accountCategoryId,
        planDate: this.plan.planDate.replace('-', '')
      }
      const res = await this.$u.api.getExpenditureAmtSummary(params)
      this.expenditureAmtSummary = res
    },
    // 按键被点击(点击退格键不会触发此事件)
    valChange(val) {
      if (this.plan.expenditureAmt.length > 10) return
      this.plan.expenditureAmt += val
    },
    // 退格键被点击
    backspace() {
      // 删除value的最后一个字符
      if (this.plan.expenditureAmt.length)
        this.plan.expenditureAmt = this.plan.expenditureAmt.substr(0, this.plan.expenditureAmt.length - 1)
    },
    /**
     * 保存
     */
    async update() {
      // 校验
      if (!this.plan.expenditureAmt) {
        return
      }
      if (!this.plan.planDate) {
        return
      }
      if (!this.confirmIndex == 0) {
        return
      }

      // 设置不能再次点击 2秒后恢复
      this.confirmIndex += 1
      setTimeout(() => {
        this.confirmIndex = 0
      }, 2000)

      let planDate = this.plan.planDate.replace('-', '')
      let params = {
        id: this.plan.id,
        expenditureAmt: this.plan.expenditureAmt,
        planDate: planDate,
        accountBookId: this.plan.accountBookId,
        accountCategoryId: this.plan.accountCategoryId
      }
      const res = await this.$u.api.upAccountPlan(params)
      this.$u.toast('更新成功，正在为您跳转记录列表')

      setTimeout(() => {
        uni.navigateBack({
          delta: 1,
          success: function () {
            uni.$emit('refreshPlanPage')
          }
        })
      }, 1500)
    },
    /**
     * 计划月份赋值
     * @param {Object} e
     */
    timeConfirm(e) {
      let input = ''
      if (this.params.year) input += e.year
      if (this.params.month) input += '-' + e.month

      this.plan.planDate = input
    }
  }
}
</script>

<style lang="scss" scoped>
.container {
  width: 750rpx;
  color: #333333;

  .bg-top {
    margin-top: -1rpx;
    width: 750rpx;
    height: 220rpx;
    padding-top: 50rpx;
    border-radius: 0 0 20% 20%;

    .top-box {
      width: 700rpx;
      background-color: #ffffff;
      margin: 0 auto;
      border-radius: 20rpx;
      padding: 20rpx 30rpx 0rpx;
      position: relative;

      .qh-title {
        width: 100%;
        height: 60rpx;
        line-height: 65rpx;
      }
    }
  }

  .saveRecord {
    background-color: #dbf1e1;
    color: $u-tips-color;
    border: none;
    border-radius: 10px;
    font-size: 30rpx;

    &::after {
      border: none;
    }
  }
}

.category-subsection {
  width: 250rpx;
}

.input-width-250 {
  width: 250rpx;
}
</style>
